﻿//-----------------------------------------------------------------------
// <copyright file="OutputFormatAttribute.cs" company="OverrideThis">
//     Copyright (c) 2010 OverrideThis.com
// </copyright>
//-----------------------------------------------------------------------
namespace OverrideThis.ContactManager.WebSite.Infrastructure.ActionFilters
{
    using System;
    using System.Web.Mvc;

    public class OutputFormatAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var format = filterContext.RequestContext.HttpContext.Request.Params["f"];
            if (string.IsNullOrWhiteSpace(format))
                return;
            var model = filterContext.Controller.ViewData.Model;
            if (format.Equals("json", StringComparison.InvariantCultureIgnoreCase))
            {
                if (model != null)
                {
                    var result = new JsonResult();
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    result.Data = model;
                    filterContext.Result = result;
                }
            }

        }
    }
}